package cn.gxufe.reliable.message.admin.controller;

import cn.gxufe.reliable.message.admin.service.ReliableMessageService;
import cn.gxufe.reliable.message.common.Message;
import cn.gxufe.reliable.message.common.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import static cn.gxufe.reliable.message.common.Message.SOURCE_SERVICE_NAME;

/**
 * @author yingjie.rong
 **/
@RestController
@RequestMapping("/")
public class RMSController {

    @Autowired
    private ReliableMessageService reliableMessageService;
    /**
     * prepare
     * @param message
     * @return
     */
    @RequestMapping(value = "/message/prepare",method = RequestMethod.PUT)
    public ResultVo prepare(@RequestBody Message message, HttpServletRequest request){
        return reliableMessageService.prepare(message, getSourceService(request));
    }

    /**
     * finish
     * @param message
     * @return
     */
    @RequestMapping(value = "/message/finish",method = RequestMethod.POST)
    public ResultVo finish(@RequestBody Message message,HttpServletRequest request){
        return reliableMessageService.finish(message,getSourceService(request));
    }

    /**
     * cancel
     * @param message
     * @return
     */
    @RequestMapping(value = "/message/cancel",method = RequestMethod.POST)
    public ResultVo cancel(@RequestBody Message message,HttpServletRequest request){
        return reliableMessageService.cancel(message,getSourceService(request));
    }

    private String getSourceService(HttpServletRequest request){
        String sourceService = request.getHeader(SOURCE_SERVICE_NAME);
        if(StringUtils.isEmpty(sourceService)){
            throw new IllegalArgumentException("must set sourceService in headers");
        }
        return sourceService;
    }

}
